import { useSelector, useDispatch } from "react-redux";
import { useCallback } from "react";
import Creators from "../store/actions";
import ShoppingCartAPi from "../api/shoppingCart";
import OrderApi from "../api/order";

export const useShoppingCart = () => {
  const dispatch = useDispatch();
  // 获取全局shoppingCart数据
  const shoppingCart = useSelector(state => state.shoppingCart);

  // 获取当页数据
  const { curPage, eachPage } = shoppingCart;
  const getShoppingCart = useCallback(async () => {
    const data = await ShoppingCartAPi.get({ curPage, eachPage });
    dispatch(Creators.getShoppingCart(data));
  }, [dispatch, curPage, eachPage]);

  // 修改当前页
  const setCurPage = useCallback((curPage) => {
    dispatch(Creators.cartSetCurPage({ curPage }))
  }, [dispatch]);

  // 修改每页显示条数
  const setEachPage = useCallback((eachPage) => {
    dispatch(Creators.cartSetEachPage({ eachPage }));
  }, [dispatch]);

  // 删除购物车商品
  const delComm = useCallback(async (_id) => {
    const data = await ShoppingCartAPi.delComm(_id);
    return data;
  }, []);



  // 修改商品数量
  const changeCount = useCallback(async ({ count, _id }) => {
    return await ShoppingCartAPi.changeCount({ count, _id });
  }, []);

  // 通过用户id查找对应购物车商品
  const findCart = useCallback(async (user_id) => {
    const searchRows = await ShoppingCartAPi.findCart(user_id);
    dispatch(Creators.cartGetSearch({ searchRows }));
  }, [dispatch])

  // 通过商品id找到商品整条数据
  const findComm = useCallback(async (commodity_id) => {
    return await ShoppingCartAPi.findComm(commodity_id);
  }, []);

  // 生成订单
  const createOrderHook = useCallback(async (data) => {
    return await OrderApi.addOrder(data);
  })



  return [shoppingCart, { getShoppingCart, setCurPage, setEachPage, delComm, changeCount, findCart, findComm, createOrderHook }]
}